package com.hmall.search.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hmall.common.client.ItemClient;
import com.hmall.common.dto.Item;
import com.hmall.common.dto.PageDTO;
import com.hmall.search.pojo.ItemDoc;
import com.hmall.search.pojo.ItemParams;
import com.hmall.search.service.ISearchService;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class SearchServiceImpl implements ISearchService {
    @Autowired
    private RestHighLevelClient client;

    private static final ObjectMapper MAPPER = new ObjectMapper();

    /**
     * 自动补全
     *
     * @param prefix
     * @return
     */
    @Override
    public List<String> getSuggestion(String prefix) {
        try {
            SearchRequest request = new SearchRequest("item");
            request.source().fetchSource(new String[0], null);
            request.source().suggest(new SuggestBuilder().addSuggestion(
                    "my_suggestion", SuggestBuilders.completionSuggestion("suggestion")
                            .prefix(prefix).skipDuplicates(true).size(10)));
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            //响应解析
            Suggest suggest = response.getSuggest();
            CompletionSuggestion suggestions = suggest.getSuggestion("my_suggestion");
            List<CompletionSuggestion.Entry.Option> options = suggestions.getOptions();
            List<String> list = new ArrayList<>(options.size());
            for (CompletionSuggestion.Entry.Option option : options) {
                String s = option.getText().string();
                list.add(s);
            }
//            List<String> collect = options.stream().map(CompletionSuggestion.Entry.Option::getText)
//                    .map(Text::string).collect(Collectors.toList());
            return list;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 过滤项聚合
     *
     * @return
     * @paramitemParams
     * @Override
     */
    public Map<String, List<String>> getFilters(ItemParams itemParams) {
        try {
            SearchRequest request = new SearchRequest("item");
            buildBasicQuery(itemParams, request);
            request.source().size(0);
            //聚合
            request.source().aggregation(AggregationBuilders.terms("brandAgg").field("brand").size(20));
            request.source().aggregation(AggregationBuilders.terms("categoryAgg").field("category").size(20));
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            //解析响应
            Map<String, List<String>> map = new HashMap<>();
            Aggregations aggregations = response.getAggregations();
            List<String> brandList = getAggByName(aggregations, "brandAgg");
            map.put("品牌", brandList);
            List<String> categoryList = getAggByName(aggregations, "categoryAgg");
            map.put("分类", categoryList);
            return map;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 基本搜索功能
     *
     * @param itemParams
     * @return
     */
    @Override
    public PageDTO<ItemDoc> getlst(ItemParams itemParams) {
        try {
            SearchRequest request = new SearchRequest("item");
            buildBasicQuery(itemParams, request);
            //排序
            request.source().sort("sortBy", SortOrder.ASC);
            //分页
            int page = itemParams.getPage();
            int size = itemParams.getSize();
            request.source().from((page - 1) * size).size(size);
            //高亮
            request.source().highlighter(new HighlightBuilder().field("name").requireFieldMatch(false));

            SearchResponse response = client.search(request, RequestOptions.DEFAULT);

            SearchHits searchHits = response.getHits();
            long value = searchHits.getTotalHits().value;
            SearchHit[] hits = searchHits.getHits();
            List<ItemDoc> list = new ArrayList<>(hits.length);
            for (SearchHit hit : hits) {
                String s = hit.getSourceAsString();
                ItemDoc itemDoc = MAPPER.readValue(s, ItemDoc.class);
                Map<String, HighlightField> map = hit.getHighlightFields();
                if (!CollectionUtils.isEmpty(map)) {
                    HighlightField highlightField = map.get("mane");
                    if (highlightField != null) {
                        String name = highlightField.getFragments()[0].string();
                        itemDoc.setName(name);
                    }
                    list.add(itemDoc);
                }
            }
            return new PageDTO<>(value, list);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Autowired
    private ItemClient itemClient;

    @Override
    public void insertById(Long id) {
        try {
            Item byId = itemClient.getById(id);
            ItemDoc itemDoc = new ItemDoc(byId);
            IndexRequest request = new IndexRequest("item").id(id.toString());
            request.source(MAPPER.writeValueAsString(itemDoc), XContentType.JSON);
            client.index(request,RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void deleteById(Long id) {
        try {
            DeleteRequest deleteRequest = new DeleteRequest("item", id.toString());
            client.delete(deleteRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private List<String> getAggByName(Aggregations aggregations, String aggName) {
        Terms brandTerns = aggregations.get(aggName);
        List<? extends Terms.Bucket> buckets = brandTerns.getBuckets();
        List<String> list = new ArrayList<>();
        for (Terms.Bucket bucket : buckets) {
            String key = bucket.getKeyAsString();
            list.add(key);
        }
        return list;
    }

    private void buildBasicQuery(ItemParams itemParams, SearchRequest request) {
        // 1.构建BooleanQuery
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        // 2.关键字搜索
        String key = itemParams.getKey();
        if (StringUtils.isNotBlank(key)) {
            boolQuery.must(QueryBuilders.matchQuery("all", key));
        } else {
            boolQuery.must(QueryBuilders.matchAllQuery());
        }
        // 3.分类名称
        if (StringUtils.isNotBlank(itemParams.getCategory())) {
            boolQuery.filter(QueryBuilders.termQuery("category", itemParams.getCategory()));
        }
        // 4.品牌名称
        if (StringUtils.isNotBlank(itemParams.getBrand())) {
            boolQuery.filter(QueryBuilders.termQuery("brand", itemParams.getBrand()));
        }
        // 5.价格
        if (itemParams.getMinPrice() != null && itemParams.getMaxPrice() != null) {
            boolQuery.filter(QueryBuilders
                    .rangeQuery("price")
                    .gte(itemParams.getMinPrice() * 100)
                    .lte(itemParams.getMaxPrice() * 100)
            );
        }
        // 7.放入source
        request.source().query(boolQuery);


    }
}
